<template>
  <div class="login-container">
    <el-card>
      <img src="../../assets/logo.fefe7e03.png" alt="" class="logo">

      <el-form :rules="rules" :model="form" ref="formRef">
        <el-form-item prop="mobile">
          <el-input placeholder="请输入手机号" v-model="form.mobile"></el-input>
          <el-button type="info" size="small" @click="onSendSms">发送验证码</el-button>
        </el-form-item>

        <el-form-item prop="code">
          <el-input placeholder="请输入验证码" v-model="form.code"></el-input>
        </el-form-item>

        <el-form-item>
          <el-checkbox >我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loginBtn">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { userLoginAPI, sendSmsAPI } from '../../api/index.js'
import { setItem } from '../../utils/storage.js'
export default {
  name: 'loginIndex',
  data () {
    return {
      form: {
        mobile: '',
        code: ''
      },
      rules: {
        // 校验手机号
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3|5|7|8]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        // 校验密码
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码6个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 发送验证码
    async onSendSms () {
      try {
        await sendSmsAPI(this.form.mobile)
        console.log('验证码发送成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 点击登录按钮，校验整体表单
    loginBtn () {
      this.$refs.formRef.validate(async valid => {
        console.log(valid)
        try {
          const { data: res } = await userLoginAPI({
            mobile: this.form.mobile,
            code: this.form.code
          })
          setItem('USER_TOKEN', res.data)
          this.$router.push({ path: '/layout/home' })
        } catch (error) {
          console.log(error)
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.login-container{
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url(../../assets/login.1e94db24.png);
  .el-card{
    width: 440px;
    height: 380px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);
    .logo{
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }
    .el-form{
      padding: 0 20px;
      .el-button{
        width: 100%;
      }
    }

  }
}
</style>
